package array;

public class NextGeneration {

    public static int[][] nextGeneration(int[][] grid) {
        int height = grid.length;
        int widht = grid[0].length;
        int[][] next = new int[height][widht];

        // 计算grid[row][col]的活邻居数量
        class NeighborCount {
            int countLiveNeighbors(int row, int col) {
                int count = 0;
                // 检查8个方向的邻居
                for (int i = -1; i <= 1; i++) {
                    for (int j = -1; j <= 1; j++) {
                        // 跳过自己
                        if (i == 0 && j == 0) {
                            continue;
                        }
                        int newRow = row + i;
                        int newCol = col + j;

                        // 检查边界
                        if (newRow >= 0 && newRow < height && newCol >= 0 && newCol < widht) {
                            count += grid[newRow][newCol];
                        }
                    }
                }
                return count;
            }
        }

        NeighborCount nc = new NeighborCount();
        // 遍历每个细胞，应用游戏规则
        for (int row = 0; row < height; row++) {
            for (int col = 0; col < widht; col++) {
                int currentCell = grid[row][col];
                int liveNeighbors = nc.countLiveNeighbors(row, col);
                if (currentCell == 1) {
                    // 活细胞的规则
                    if (liveNeighbors < 2) {
                        // 规则1：邻居少于2个，死于孤独
                        next[row][col] = 0;
                    } else if (liveNeighbors == 2 || liveNeighbors == 3) {
                        // 规则2：邻居等于2个或3个，继续生存
                        next[row][col] = 1;
                    } else {
                        // 规则3：邻居多于3个，死于过度拥挤
                        next[row][col] = 0;
                    }
                } else {
                    // 死细胞的规则
                    if (liveNeighbors == 3) {
                        // 规则4：恰好3个活邻居，因繁殖而复活
                        next[row][col] = 1;
                    }
                }
            }
        }
        return next;
    }
}
